// 应用状态管理
class WordCardApp {
    constructor() {
        this.words = [];
        this.isLoading = true;
        this.currentIndex = 0;
        this.currentMode = 'sequential';
        this.favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
        this.studiedWords = JSON.parse(localStorage.getItem('studiedWords') || '[]');
        this.currentWordList = [...this.words];
        this.isShowingInfo = false;
        
        // 语音设置
        this.voiceSettings = JSON.parse(localStorage.getItem('voiceSettings') || JSON.stringify({
            provider: 'local', // 默认改为本地
            rate: 0.8,
            pitch: 1.0,
            volume: 1.0,
            systemVoice: ''
        }));
        
        this.initializeElements();
        this.bindEvents();
        this.loadVoiceSettings();
        
        // 异步加载单词数据
        this.loadWords().then(() => {
            this.loadLastPosition(); // 加载上次的位置
            this.updateDisplay();
            this.updateStats();
        });
    }

    // 异步加载单词数据
    async loadWords() {
        try {
            const response = await fetch('dict.json');
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            this.words = await response.json();
            console.log(`✓ 成功加载 ${this.words.length} 个单词`);
            this.isLoading = false;
            this.currentWordList = [...this.words];
            return true;
        } catch (error) {
            console.error('加载单词数据失败:', error);
            // 回退到 dict.js (如果存在)
            if (typeof chineseWords !== 'undefined') {
                this.words = chineseWords;
                console.log(`✓ 回退使用 dict.js，加载 ${this.words.length} 个单词`);
                this.isLoading = false;
                this.currentWordList = [...this.words];
                return true;
            }
            this.showToast('加载单词数据失败，请刷新页面重试', 'error');
            return false;
        }
    }

    // 初始化DOM元素
    initializeElements() {
        this.elements = {
            chineseWord: document.getElementById('chineseWord'),
            pinyin: document.getElementById('pinyin'),
            meaning: document.getElementById('meaning'),
            wordInfo: document.getElementById('wordInfo'),
            wordCard: document.getElementById('wordCard'),
            audioBtn: document.getElementById('audioBtn'),
            favoriteBtn: document.getElementById('favoriteBtn'),
            prevBtn: document.getElementById('prevBtn'),
            nextBtn: document.getElementById('nextBtn'),
            currentIndex: document.getElementById('currentIndex'),
            totalCount: document.getElementById('totalCount'),
            totalWords: document.getElementById('totalWords'),
            favoriteCount: document.getElementById('favoriteCount'),
            studiedCount: document.getElementById('studiedCount'),
            toast: document.getElementById('toast'),
            modeButtons: document.querySelectorAll('.mode-btn'),
            modeSelect: document.getElementById('modeSelect'),
            
            // 跳转相关元素
            jumpBtn: document.getElementById('jumpBtn'),
            jumpOverlay: document.getElementById('jumpOverlay'),
            closeJumpBtn: document.getElementById('closeJumpBtn'),
            jumpToBtn: document.getElementById('jumpToBtn'),
            jumpInput: document.getElementById('jumpInput'),
            jumpMaxHint: document.getElementById('jumpMaxHint'),
            
            // 设置相关元素
            settingsBtn: document.getElementById('settingsBtn'),
            settingsOverlay: document.getElementById('settingsOverlay'),
            closeSettingsBtn: document.getElementById('closeSettingsBtn'),
            saveSettingsBtn: document.getElementById('saveSettingsBtn'),
            testVoiceBtn: document.getElementById('testVoiceBtn'),
            // 语音来源（本地/在线）
            modeSelect: document.getElementById('modeSelect'),
            
            // 语音设置元素
            voiceProviderRadios: document.querySelectorAll('input[name="voiceProvider"]'),
            rateSlider: document.getElementById('rateSlider'),
            pitchSlider: document.getElementById('pitchSlider'),
            volumeSlider: document.getElementById('volumeSlider'),
            rateValue: document.getElementById('rateValue'),
            pitchValue: document.getElementById('pitchValue'),
            volumeValue: document.getElementById('volumeValue'),
            systemVoiceSelect: document.getElementById('systemVoiceSelect'),
            systemVoiceGroup: document.getElementById('systemVoiceGroup'),
            baiduConfigGroup: document.getElementById('baiduConfigGroup')
        };
    }

    // 绑定事件监听器
    bindEvents() {
        // 单词卡片点击事件
        this.elements.wordCard.addEventListener('click', (e) => {
            if (!e.target.closest('.audio-btn') && !e.target.closest('.favorite-btn')) {
                this.toggleWordInfo();
            }
        });

        // 音频播放按钮
        this.elements.audioBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.playAudio();
        });

        // 收藏按钮
        this.elements.favoriteBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.toggleFavorite();
        });

        // 导航按钮
        this.elements.prevBtn.addEventListener('click', () => this.previousWord());
        this.elements.nextBtn.addEventListener('click', () => this.nextWord());

        // 模式切换（兼容：如果有按钮则支持点击；如果是下拉则监听 change）
        if (this.elements.modeButtons && this.elements.modeButtons.length > 0) {
            this.elements.modeButtons.forEach(btn => {
                btn.addEventListener('click', () => {
                    const mode = btn.dataset.mode;
                    this.switchMode(mode);
                    // 同步 select（若存在）
                    if (this.elements.modeSelect) this.elements.modeSelect.value = mode;
                });
            });
        }
        if (this.elements.modeSelect) {
            this.elements.modeSelect.addEventListener('change', (e) => {
                const mode = e.target.value;
                this.switchMode(mode);
            });
        }

        // 跳转按钮事件
        if (this.elements.jumpBtn) {
            this.elements.jumpBtn.addEventListener('click', () => this.openJumpDialog());
        }
        if (this.elements.closeJumpBtn) {
            this.elements.closeJumpBtn.addEventListener('click', () => this.closeJumpDialog());
        }
        if (this.elements.jumpToBtn) {
            this.elements.jumpToBtn.addEventListener('click', () => this.jumpToCard());
        }
        if (this.elements.jumpOverlay) {
            this.elements.jumpOverlay.addEventListener('click', (e) => {
                if (e.target === this.elements.jumpOverlay) {
                    this.closeJumpDialog();
                }
            });
        }
        if (this.elements.jumpInput) {
            this.elements.jumpInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.jumpToCard();
                }
            });
        }


        // 设置按钮事件
        this.elements.settingsBtn.addEventListener('click', () => this.openSettings());
        this.elements.closeSettingsBtn.addEventListener('click', () => this.closeSettings());
        this.elements.saveSettingsBtn.addEventListener('click', () => this.saveSettings());
        this.elements.testVoiceBtn.addEventListener('click', () => this.testVoice());
        
        // 设置面板点击外部关闭
        this.elements.settingsOverlay.addEventListener('click', (e) => {
            if (e.target === this.elements.settingsOverlay) {
                this.closeSettings();
            }
        });
        
        // 语音提供商选择
        this.elements.voiceProviderRadios.forEach(radio => {
            radio.addEventListener('change', () => this.updateVoiceProviderUI());
        });
        
        // 滑块事件
        this.elements.rateSlider.addEventListener('input', (e) => {
            this.elements.rateValue.textContent = e.target.value;
        });
        this.elements.pitchSlider.addEventListener('input', (e) => {
            this.elements.pitchValue.textContent = e.target.value;
        });
        this.elements.volumeSlider.addEventListener('input', (e) => {
            this.elements.volumeValue.textContent = e.target.value;
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            // 如果设置面板或跳转面板打开，不处理快捷键
            if (!this.elements.settingsOverlay.classList.contains('hidden') || 
                (this.elements.jumpOverlay && !this.elements.jumpOverlay.classList.contains('hidden'))) {
                return;
            }
            
            switch(e.key) {
                case 'ArrowLeft':
                    e.preventDefault();
                    this.previousWord();
                    break;
                case 'ArrowRight':
                    e.preventDefault();
                    this.nextWord();
                    break;
                case ' ':
                    e.preventDefault();
                    this.toggleWordInfo();
                    break;
                case 'f':
                case 'F':
                    e.preventDefault();
                    this.toggleFavorite();
                    break;
                case 'p':
                case 'P':
                    e.preventDefault();
                    this.playAudio();
                    break;
                case 'j':
                case 'J':
                    e.preventDefault();
                    this.openJumpDialog();
                    break;
                case 'Escape':
                    e.preventDefault();
                    this.closeSettings();
                    this.closeJumpDialog();
                    break;
            }
        });
    }

    // 切换单词信息显示
    toggleWordInfo() {
        this.isShowingInfo = !this.isShowingInfo;
        
        // 添加卡片翻转动画
        this.elements.wordCard.classList.add('clicked');
        setTimeout(() => {
            this.elements.wordCard.classList.remove('clicked');
        }, 600);

        if (this.isShowingInfo) {
            this.elements.wordInfo.classList.remove('hidden');
            this.markAsStudied();
        } else {
            this.elements.wordInfo.classList.add('hidden');
        }
    }

    // 播放音频 - 根据用户设置选择语音方案
    // 优先播放本地音频（./voice 下），不存在则回退到在线方案
    async playAudio() {
        const currentWord = this.getCurrentWord();
        if (!currentWord) return;
        
        // 本地播放优先：按照批处理脚本的输出命名规则尝试查找
        const localSlug = `${currentWord.id}_${currentWord.word}`.replace(/\s+/g, '_').replace(/[^\w\u4e00-\u9fff_]/g, '').slice(0, 40);
        const localUrlMp3 = `voice/${localSlug}.mp3`;
        const localUrlWav = `voice/${localSlug}.wav`;
        
        // 如果设置为本地，或本地文件存在，就优先尝试本地
        const preferLocal = (this.voiceSettings.provider === 'local');

        const tryPlayLocal = async (url) => {
            return new Promise((resolve, reject) => {
                const audio = new Audio();
                audio.src = url + `?t=${Date.now()}`; // 防缓存
                audio.preload = 'auto';
                audio.oncanplay = () => {
                    audio.play().then(resolve).catch(reject);
                };
                audio.onerror = () => reject(new Error('本地音频不可用'));
            });
        };

        try {
            if (preferLocal) {
                try {
                    await tryPlayLocal(localUrlMp3);
                    return;
                } catch {}
                try {
                    await tryPlayLocal(localUrlWav);
                    return;
                } catch {}
                // 本地优先但未找到，继续走在线方案
            } else {
                // 即使非 local，如果本地存在也可作为快速路径
                try {
                    await tryPlayLocal(localUrlMp3);
                    return;
                } catch {}
            }
        } catch (error) {
            console.log('本地语音尝试失败:', error);
        }

        // 音频按钮动画效果和加载状态
        this.elements.audioBtn.style.transform = 'scale(0.9)';
        this.elements.audioBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        
        const resetButton = () => {
            this.elements.audioBtn.style.transform = 'scale(1)';
            this.elements.audioBtn.innerHTML = '<i class="fas fa-volume-up"></i>';
        };

        try {
            // 根据用户设置选择语音方案（local 已在前面优先处理）
            switch (this.voiceSettings.provider) {
                case 'edge':
                    await this.playEdgeTTS(currentWord.word);
                    break;
                case 'baidu':
                    try {
                        await this.playBaiduTTSImproved(currentWord.word);
                    } catch (error) {
                        console.log('百度语音失败，尝试备用方案:', error.message);
                        // 如果百度语音失败，使用系统语音
                        await this.playWebSpeechTTS(currentWord.word);
                    }
                    break;
                case 'system':
                    await this.playWebSpeechTTS(currentWord.word);
                    break;
                case 'auto':
                default:
                    // 智能选择：按优先级尝试
                    const voiceMethods = [
                        { name: 'Edge TTS', method: () => this.playEdgeTTS(currentWord.word) },
                        { name: '百度语音', method: () => this.playBaiduTTS(currentWord.word) },
                        { name: 'ResponsiveVoice', method: () => this.playResponsiveVoiceTTS(currentWord.word) },
                        { name: '系统语音', method: () => this.playWebSpeechTTS(currentWord.word) }
                    ];

                    let success = false;
                    for (const voiceMethod of voiceMethods) {
                        try {
                            console.log(`尝试使用 ${voiceMethod.name}`);
                            await voiceMethod.method();
                            success = true;
                            break;
                        } catch (error) {
                            console.log(`${voiceMethod.name} 不可用:`, error.message);
                            continue;
                        }
                    }
                    
                    if (!success) {
                        throw new Error('所有语音方案都不可用');
                    }
                    break;
            }
            
            resetButton();
        } catch (error) {
            resetButton();
            this.showToast('语音播放失败，请检查网络连接或浏览器设置', 'error');
        }
    }

    // 百度语音API方案（更自然的人声）
    async playBaiduTTS(text) {
        // 尝试多个百度语音接口
        const apiConfigs = [
            {
                url: `https://fanyi.baidu.com/gettts?lan=zh&text=${encodeURIComponent(text)}&spd=3&source=web`,
                name: '百度翻译语音'
            },
            {
                url: `https://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=2&text=${encodeURIComponent(text)}`,
                name: '百度TTS服务'
            },
            {
                // 使用代理方式避免跨域问题
                url: `https://translate.google.com/translate_tts?ie=UTF-8&tl=zh&client=tw-ob&q=${encodeURIComponent(text)}`,
                name: 'Google TTS (中文)'
            }
        ];
        
        for (const config of apiConfigs) {
            try {
                console.log(`尝试 ${config.name}:`, config.url);
                
                const audio = new Audio();
                
                // 设置音频属性
                audio.crossOrigin = 'anonymous';
                audio.preload = 'auto';
                
                // 创建一个Promise来处理音频加载和播放
                await new Promise((resolve, reject) => {
                    const timeout = setTimeout(() => {
                        audio.src = '';
                        reject(new Error('音频加载超时'));
                    }, 8000);
                    
                    // 监听各种事件
                    audio.onloadstart = () => {
                        console.log('开始加载音频...');
                    };
                    
                    audio.oncanplay = () => {
                        console.log('音频可以播放');
                        clearTimeout(timeout);
                        audio.play()
                            .then(() => {
                                console.log('音频播放成功');
                                resolve();
                            })
                            .catch(reject);
                    };
                    
                    audio.onerror = (e) => {
                        console.error('音频加载错误:', e);
                        clearTimeout(timeout);
                        reject(new Error(`音频加载失败: ${audio.error?.message || '未知错误'}`));
                    };
                    
                    audio.onabort = () => {
                        clearTimeout(timeout);
                        reject(new Error('音频加载被中断'));
                    };
                    
                    // 设置音频源并开始加载
                    audio.src = config.url;
                    audio.load();
                });
                
                // 静默播放，不显示提示
                return;
                
            } catch (error) {
                console.log(`${config.name} 不可用:`, error.message);
                continue;
            }
        }
        
        throw new Error('所有在线语音服务不可用，可能是网络问题或跨域限制');
    }

    // 尝试使用Microsoft Edge的高质量语音
    async playEdgeTTS(text) {
        if (!window.speechSynthesis) {
            throw new Error('浏览器不支持语音合成');
        }

        return new Promise((resolve, reject) => {
            // 停止当前播放
            speechSynthesis.cancel();
            
            const utterance = new SpeechSynthesisUtterance(text);
            
            // Edge浏览器的高质量中文语音配置
            utterance.lang = 'zh-CN';
            utterance.rate = this.voiceSettings.rate;
            utterance.pitch = this.voiceSettings.pitch;
            utterance.volume = this.voiceSettings.volume;
            
            // 查找最佳语音
            const voices = speechSynthesis.getVoices();
            const edgeVoices = voices.filter(voice => 
                voice.name.includes('Microsoft') && 
                (voice.name.includes('Xiaoxiao') || 
                 voice.name.includes('Yunyang') || 
                 voice.name.includes('Xiaomo') ||
                 voice.name.includes('Xiaoyi') ||
                 voice.name.includes('Kangkang') ||
                 voice.name.includes('Yaoyao'))
            );
            
            if (edgeVoices.length > 0) {
                utterance.voice = edgeVoices[0];
            } else {
                // 如果没有Edge语音，查找其他高质量中文语音
                const chineseVoices = voices.filter(voice => 
                    voice.lang.includes('zh') && 
                    (voice.name.includes('Google') || voice.name.includes('Apple'))
                );
                
                if (chineseVoices.length > 0) {
                    utterance.voice = chineseVoices[0];
                } else {
                    throw new Error('未找到高质量中文语音');
                }
            }
            
            utterance.onend = () => {
                console.log('Edge语音播放完成');
                resolve();
            };
            
            utterance.onerror = (event) => {
                console.error('Edge语音播放错误:', event.error);
                reject(new Error(`语音播放失败: ${event.error}`));
            };
            
            speechSynthesis.speak(utterance);
        });
    }

    // 新增：使用Web Audio API创建简单的语音提示
    async playSimpleTTS(text) {
        // 如果在线语音都不可用，使用简单的提示音
        try {
            // 创建音频上下文
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            
            // 创建简单的提示音序列来表示文字
            const duration = 0.1;
            const frequencies = [440, 523, 659, 784]; // C大调音阶
            
            for (let i = 0; i < Math.min(text.length, 4); i++) {
                const oscillator = audioContext.createOscillator();
                const gainNode = audioContext.createGain();
                
                oscillator.connect(gainNode);
                gainNode.connect(audioContext.destination);
                
                oscillator.frequency.setValueAtTime(frequencies[i % frequencies.length], audioContext.currentTime);
                oscillator.type = 'sine';
                
                gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + duration);
                
                oscillator.start(audioContext.currentTime + i * duration);
                oscillator.stop(audioContext.currentTime + (i + 1) * duration);
            }
            
            // 静默播放音频提示
            
            // 等待音频播放完成
            await new Promise(resolve => setTimeout(resolve, text.length * 100 + 200));
            
        } catch (error) {
            throw new Error('音频功能不可用');
        }
    }

    // 改进的百度语音实现，添加网络检测
    async playBaiduTTSImproved(text) {
        // 首先检测网络连接
        try {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 3000);
            
            const response = await fetch('https://www.baidu.com/favicon.ico', {
                method: 'HEAD',
                signal: controller.signal,
                mode: 'no-cors'
            });
            
            clearTimeout(timeoutId);
            console.log('网络连接正常，尝试百度语音');
            
        } catch (error) {
            throw new Error('网络连接不可用，无法使用在线语音服务');
        }
        
        // 尝试百度语音API
        const apiUrl = `https://fanyi.baidu.com/gettts?lan=zh&text=${encodeURIComponent(text)}&spd=3&source=web`;
        
        try {
            const audio = new Audio();
            
            // 设置更宽松的跨域策略
            audio.crossOrigin = 'anonymous';
            audio.preload = 'metadata';
            
            await new Promise((resolve, reject) => {
                const timeout = setTimeout(() => {
                    audio.src = '';
                    reject(new Error('百度语音加载超时'));
                }, 10000);
                
                audio.addEventListener('loadeddata', () => {
                    console.log('百度语音数据加载完成');
                    clearTimeout(timeout);
                    audio.play()
                        .then(() => {
                            console.log('百度语音播放成功');
                            resolve();
                        })
                        .catch(reject);
                });
                
                audio.addEventListener('error', (e) => {
                    console.error('百度语音加载错误:', e);
                    clearTimeout(timeout);
                    reject(new Error('百度语音服务暂时不可用'));
                });
                
                // 设置音频源
                audio.src = apiUrl;
            });
            
            // 静默播放，不显示提示
            
        } catch (error) {
            console.error('百度语音播放失败:', error);
            throw new Error(`百度语音不可用: ${error.message}`);
        }
    }

    // 优化的Web Speech API方案
    playWebSpeechTTS(text) {
        return new Promise((resolve, reject) => {
            // 停止当前播放
            speechSynthesis.cancel();
            
            const utterance = new SpeechSynthesisUtterance(text);
            
            // 使用用户设置的参数
            utterance.lang = 'zh-CN';
            utterance.rate = this.voiceSettings.rate;
            utterance.pitch = this.voiceSettings.pitch;
            utterance.volume = this.voiceSettings.volume;
            
            // 等待语音列表加载完成
            const setVoice = () => {
                const voices = speechSynthesis.getVoices();
                let selectedVoice = null;
                
                // 如果用户指定了系统语音，优先使用
                if (this.voiceSettings.systemVoice) {
                    selectedVoice = voices.find(voice => voice.name === this.voiceSettings.systemVoice);
                }
                
                // 如果没有指定或找不到，使用默认逻辑
                if (!selectedVoice) {
                    const preferredVoices = [
                        'Microsoft Yaoyao - Chinese (Simplified, PRC)',
                        'Microsoft Kangkang - Chinese (Simplified, PRC)',
                        'Google 普通话（中国大陆）',
                        'Ting-Ting',
                        'Sin-ji',
                        'Mei-Jia'
                    ];
                    
                    // 按优先级查找语音
                    for (const voiceName of preferredVoices) {
                        selectedVoice = voices.find(voice => 
                            voice.name.includes(voiceName) || 
                            voice.name.includes('Chinese') ||
                            voice.name.includes('中文') ||
                            voice.name.includes('普通话')
                        );
                        if (selectedVoice) break;
                    }
                    
                    // 如果没找到，使用任何中文语音
                    if (!selectedVoice) {
                        selectedVoice = voices.find(voice => 
                            voice.lang.includes('zh') || 
                            voice.lang.includes('cmn')
                        );
                    }
                }
                
                if (selectedVoice) {
                    utterance.voice = selectedVoice;
                    console.log('使用语音:', selectedVoice.name);
                }
                
                speechSynthesis.speak(utterance);
            };
            
            // 如果语音列表已加载，直接设置；否则等待加载
            if (speechSynthesis.getVoices().length > 0) {
                setVoice();
            } else {
                speechSynthesis.addEventListener('voiceschanged', setVoice, { once: true });
            }
            
            // 错误处理
            utterance.onerror = (event) => {
                console.error('语音播放错误:', event.error);
                reject(new Error('语音播放失败'));
            };
            
            utterance.onend = () => {
                console.log('语音播放完成');
                resolve();
            };
        });
    }

    // 切换收藏状态
    toggleFavorite() {
        const currentWord = this.getCurrentWord();
        if (!currentWord) return;

        const wordId = currentWord.id;
        const isFavorited = this.favorites.includes(wordId);

        if (isFavorited) {
            this.favorites = this.favorites.filter(id => id !== wordId);
            this.showToast('已取消收藏');
        } else {
            this.favorites.push(wordId);
            this.showToast('已添加到收藏');
        }

        // 保存到本地存储
        localStorage.setItem('favorites', JSON.stringify(this.favorites));
        this.updateStats();

        // 如果当前是收藏模式，需要更新单词列表
        if (this.currentMode === 'favorites') {
            this.updateWordList();
            // 强制重新刷新当前单词显示
            this.updateDisplay();
        } else {
            // 更新显示状态
            this.updateFavoriteButton();
        }
    }

    // 标记为已学习
    markAsStudied() {
        const currentWord = this.getCurrentWord();
        if (!currentWord) return;

        const wordId = currentWord.id;
        if (!this.studiedWords.includes(wordId)) {
            this.studiedWords.push(wordId);
            localStorage.setItem('studiedWords', JSON.stringify(this.studiedWords));
            this.updateStats();
        }
    }

    // 上一个单词
    previousWord() {
        if (this.currentIndex > 0) {
            this.currentIndex--;
            this.updateDisplay();
            this.saveCurrentPosition();
        }
    }

    // 下一个单词
    nextWord() {
        if (this.currentIndex < this.currentWordList.length - 1) {
            this.currentIndex++;
            this.updateDisplay();
            this.saveCurrentPosition();
        }
    }
    
    // 保存当前位置到本地存储
    saveCurrentPosition() {
        const position = {
            mode: this.currentMode,
            index: this.currentIndex
        };
        localStorage.setItem('lastPosition', JSON.stringify(position));
    }
    
    // 加载上次的位置
    loadLastPosition() {
        try {
            const savedPosition = JSON.parse(localStorage.getItem('lastPosition'));
            if (savedPosition) {
                // 先切换到保存的模式
                if (savedPosition.mode) {
                    this.switchMode(savedPosition.mode, false); // 不重置索引
                }
                
                // 然后设置索引
                if (typeof savedPosition.index === 'number' && 
                    savedPosition.index >= 0 && 
                    savedPosition.index < this.currentWordList.length) {
                    this.currentIndex = savedPosition.index;
                }
            }
        } catch (error) {
            console.error('加载上次位置失败:', error);
        }
    }
    
    // 跳转到指定卡片
    jumpToCard(cardNumberFromQuick) {
        // 来源可能是弹层输入或快速输入
        const max = this.currentWordList.length;
        let cardNumber;

        if (typeof cardNumberFromQuick === 'number') {
            cardNumber = cardNumberFromQuick;
        } else if (this.elements.jumpInput) {
            const input = this.elements.jumpInput.value.trim();
            cardNumber = parseInt(input);
        }

        if (isNaN(cardNumber) || cardNumber < 1 || cardNumber > max) {
            this.showToast(`请输入有效的卡片编号 (1-${max})`, 'error');
            return;
        }

        this.currentIndex = cardNumber - 1;
        this.updateDisplay();
        this.saveCurrentPosition();

        // 关闭弹层，仅在来自弹层时
        if (!isNaN(cardNumberFromQuick)) {
            // 来自快速输入，不关闭
        } else {
            this.closeJumpDialog();
        }

        this.showToast(`已跳转到第 ${cardNumber} 张卡片`);
    }
    
    // 打开跳转对话框
    openJumpDialog() {
        if (!this.elements.jumpOverlay) return;
        
        this.elements.jumpOverlay.classList.remove('hidden');
        const max = this.currentWordList.length;
        if (this.elements.jumpInput) {
            this.elements.jumpInput.max = String(max);
            this.elements.jumpInput.min = '1';
            this.elements.jumpInput.placeholder = `输入数字 (1-${max})`;
            this.elements.jumpInput.value = this.currentIndex + 1;
            setTimeout(() => {
                this.elements.jumpInput.focus();
                this.elements.jumpInput.select();
            }, 100);
        }
        if (this.elements.jumpMaxHint) {
            this.elements.jumpMaxHint.textContent = `(最大编号：${max})`;
        }
    }
    
    // 关闭跳转对话框
    closeJumpDialog() {
        if (!this.elements.jumpOverlay) return;
        this.elements.jumpOverlay.classList.add('hidden');
    }

    // 切换练习模式
    switchMode(mode, resetIndex = true) {
        this.currentMode = mode;
        
        // 只有在需要重置索引时才设置为0
        if (resetIndex) {
            this.currentIndex = 0;
        }
        
        // 更新模式选择 UI（兼容按钮与下拉）
        if (this.elements.modeButtons && this.elements.modeButtons.length > 0) {
            this.elements.modeButtons.forEach(btn => {
                btn.classList.remove('active');
                if (btn.dataset.mode === mode) {
                    btn.classList.add('active');
                }
            });
        }
        if (this.elements.modeSelect) {
            this.elements.modeSelect.value = mode;
        }

        this.updateWordList();
        this.updateDisplay();
        
        // 保存当前位置
        this.saveCurrentPosition();
        
        // 只有在重置索引时才显示模式切换提示
        if (resetIndex) {
            const modeNames = {
                sequential: '顺序练习',
                random: '随机练习',
                favorites: '收藏练习'
            };
            this.showToast(`已切换到${modeNames[mode]}模式`);
        }
    }

    // 更新单词列表
    updateWordList() {
        switch (this.currentMode) {
            case 'sequential':
                this.currentWordList = [...this.words];
                break;
            case 'random':
                this.currentWordList = this.shuffleArray([...this.words]);
                break;
            case 'favorites':
                this.currentWordList = this.words.filter(word => 
                    this.favorites.includes(word.id)
                );
                if (this.currentWordList.length === 0) {
                    // 允许进入收藏模式，但显示空状态
                    this.currentIndex = 0;
                }
                break;
        }
        
        // 确保当前索引在有效范围内
        if (this.currentIndex >= this.currentWordList.length) {
            this.currentIndex = this.currentWordList.length - 1;
        }
        if (this.currentIndex < 0) {
            this.currentIndex = 0;
        }
    }

    // 数组随机排序
    shuffleArray(array) {
        const shuffled = [...array];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled;
    }

    // 获取当前单词
    getCurrentWord() {
        return this.currentWordList[this.currentIndex];
    }

    // 更新收藏按钮状态
    updateFavoriteButton() {
        const currentWord = this.getCurrentWord();
        if (!currentWord) return;
        
        const isFavorited = this.favorites.includes(currentWord.id);
        if (isFavorited) {
            this.elements.favoriteBtn.classList.add('favorited');
            this.elements.favoriteBtn.innerHTML = '<i class="fas fa-heart"></i>';
        } else {
            this.elements.favoriteBtn.classList.remove('favorited');
            this.elements.favoriteBtn.innerHTML = '<i class="far fa-heart"></i>';
        }
    }

    // 更新显示
    updateDisplay() {
        const currentWord = this.getCurrentWord();
        
        if (!currentWord) {
            this.elements.chineseWord.textContent = this.currentMode === 'favorites' ? '还没有收藏的单词' : '没有可显示的单词';
            this.elements.pinyin.textContent = '';
            this.elements.meaning.textContent = this.currentMode === 'favorites' ? '请先收藏一些单词' : '';
            
            // 同步跳转输入的最大值
            const maxLen = this.currentWordList.length || this.words.length;
            if (this.elements.jumpInput) this.elements.jumpInput.max = String(maxLen);
            if (this.elements.jumpMaxHint) this.elements.jumpMaxHint.textContent = `(最大编号：${maxLen})`;
            
            // 更新进度显示
            this.elements.currentIndex.textContent = '0';
            this.elements.totalCount.textContent = this.currentWordList.length;
            
            // 禁用导航按钮
            this.elements.prevBtn.disabled = true;
            this.elements.nextBtn.disabled = true;
            
            // 隐藏收藏按钮和音频按钮
            this.elements.favoriteBtn.style.display = 'none';
            this.elements.audioBtn.style.display = 'none';
            
            return;
        }

        // 更新单词显示
        this.elements.chineseWord.textContent = currentWord.word;
        this.elements.pinyin.textContent = currentWord.pinyin;
        this.elements.meaning.textContent = currentWord.meaning;

        // 重置信息显示状态
        this.isShowingInfo = false;
        this.elements.wordInfo.classList.add('hidden');

        // 更新收藏按钮状态
        this.updateFavoriteButton();

        // 更新进度显示
        this.elements.currentIndex.textContent = this.currentIndex + 1;
        this.elements.totalCount.textContent = this.currentWordList.length;

        // 同步跳转输入的最大值与提示
        const maxLen = this.currentWordList.length;
        if (this.elements.jumpInput) this.elements.jumpInput.max = String(maxLen);
        if (this.elements.jumpMaxHint) this.elements.jumpMaxHint.textContent = `(最大编号：${maxLen})`;

        // 更新导航按钮状态
        this.elements.prevBtn.disabled = this.currentIndex === 0;
        this.elements.nextBtn.disabled = this.currentIndex === this.currentWordList.length - 1;
        
        // 显示收藏按钮和音频按钮
        this.elements.favoriteBtn.style.display = 'flex';
        this.elements.audioBtn.style.display = 'flex';
    }

    // 更新统计信息
    updateStats() {
        this.elements.totalWords.textContent = this.words.length;
        this.elements.favoriteCount.textContent = this.favorites.length;
        this.elements.studiedCount.textContent = this.studiedWords.length;
    }

    // 显示提示信息
    showToast(message, type = 'success') {
        this.elements.toast.textContent = message;
        this.elements.toast.className = `toast ${type}`;
        this.elements.toast.classList.add('show');

        setTimeout(() => {
            this.elements.toast.classList.remove('show');
        }, 3000);
    }

    // 设置相关方法
    openSettings() {
        this.elements.settingsOverlay.classList.remove('hidden');
        this.loadSystemVoices();
        this.updateVoiceProviderUI();
    }

    closeSettings() {
        this.elements.settingsOverlay.classList.add('hidden');
    }

    loadVoiceSettings() {
        // 设置语音提供商（包含本地选项）
        const provider = this.voiceSettings.provider || 'local';
        const providerRadio = document.querySelector(`input[name="voiceProvider"][value="${provider}"]`);
        if (providerRadio) {
            providerRadio.checked = true;
        } else {
            // 若UI上没有匹配项，默认选中本地
            const localRadio = document.querySelector(`input[name="voiceProvider"][value="local"]`);
            if (localRadio) localRadio.checked = true;
            this.voiceSettings.provider = 'local';
        }

        // 设置滑块值
        this.elements.rateSlider.value = this.voiceSettings.rate;
        this.elements.pitchSlider.value = this.voiceSettings.pitch;
        this.elements.volumeSlider.value = this.voiceSettings.volume;
        
        // 更新显示值
        this.elements.rateValue.textContent = this.voiceSettings.rate;
        this.elements.pitchValue.textContent = this.voiceSettings.pitch;
        this.elements.volumeValue.textContent = this.voiceSettings.volume;
    }

    loadSystemVoices() {
        const voices = speechSynthesis.getVoices();
        const chineseVoices = voices.filter(voice => 
            voice.lang.includes('zh') || 
            voice.name.includes('Chinese') || 
            voice.name.includes('中文') ||
            voice.name.includes('普通话')
        );

        // 清空现有选项
        this.elements.systemVoiceSelect.innerHTML = '<option value="">自动选择</option>';

        // 添加中文语音选项
        chineseVoices.forEach(voice => {
            const option = document.createElement('option');
            option.value = voice.name;
            option.textContent = `${voice.name} (${voice.lang})`;
            if (voice.name === this.voiceSettings.systemVoice) {
                option.selected = true;
            }
            this.elements.systemVoiceSelect.appendChild(option);
        });

        // 如果没有中文语音，添加所有语音
        if (chineseVoices.length === 0) {
            voices.forEach(voice => {
                const option = document.createElement('option');
                option.value = voice.name;
                option.textContent = `${voice.name} (${voice.lang})`;
                if (voice.name === this.voiceSettings.systemVoice) {
                    option.selected = true;
                }
                this.elements.systemVoiceSelect.appendChild(option);
            });
        }
    }

    updateVoiceProviderUI() {
        const selectedProvider = document.querySelector('input[name="voiceProvider"]:checked')?.value || 'local';
        
        // 显示/隐藏相关配置组
        // 本地与自动/edge不需要额外配置
        this.elements.systemVoiceGroup.classList.toggle('hidden', selectedProvider !== 'system');
        this.elements.baiduConfigGroup.classList.toggle('hidden', selectedProvider !== 'baidu');
    }

    saveSettings() {
        // 获取当前设置
        const selectedProvider = document.querySelector('input[name="voiceProvider"]:checked')?.value || 'local';
        
        this.voiceSettings = {
            provider: selectedProvider,
            rate: parseFloat(this.elements.rateSlider.value),
            pitch: parseFloat(this.elements.pitchSlider.value),
            volume: parseFloat(this.elements.volumeSlider.value),
            systemVoice: this.elements.systemVoiceSelect.value
        };

        // 保存到本地存储
        localStorage.setItem('voiceSettings', JSON.stringify(this.voiceSettings));
        
        // 显示保存成功提示
        this.showToast('设置已保存');
        
        // 关闭设置面板
        this.closeSettings();
    }

    async testVoice() {
        const testText = '这是语音测试';
        
        // 临时更新设置进行测试
        const tempSettings = {
            provider: document.querySelector('input[name="voiceProvider"]:checked').value,
            rate: parseFloat(this.elements.rateSlider.value),
            pitch: parseFloat(this.elements.pitchSlider.value),
            volume: parseFloat(this.elements.volumeSlider.value),
            systemVoice: this.elements.systemVoiceSelect.value
        };
        
        const originalSettings = { ...this.voiceSettings };
        this.voiceSettings = tempSettings;
        
        try {
            // 测试按钮状态
            this.elements.testVoiceBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 测试中...';
            this.elements.testVoiceBtn.disabled = true;
            
            // 根据选择的提供商测试语音
            switch (tempSettings.provider) {
                case 'edge':
                    await this.playEdgeTTS(testText);
                    break;
                case 'baidu':
                    try {
                        await this.playBaiduTTSImproved(testText);
                    } catch (error) {
                        console.log('百度语音测试失败:', error.message);
                        // 显示详细错误信息
                        this.showToast(`百度语音测试失败: ${error.message}`, 'error');
                        // 测试失败时不自动切换，让用户知道具体问题
                        throw error;
                    }
                    break;
                case 'system':
                    await this.playWebSpeechTTS(testText);
                    break;
                case 'local':
                    // 如果选择本地语音，直接使用示例文件
                    await this.playTestLocalAudio();
                    break;
                case 'auto':
                default:
                    // 测试时使用系统语音，更可靠
                    await this.playWebSpeechTTS(testText);
                    break;
            }
            
            // 语音测试完成，不显示提示
        } catch (error) {
            this.showToast('语音测试失败：' + error.message, 'error');
        } finally {
            // 恢复原始设置和按钮状态
            this.voiceSettings = originalSettings;
            this.elements.testVoiceBtn.innerHTML = '<i class="fas fa-play"></i> 测试语音';
            this.elements.testVoiceBtn.disabled = false;
        }
    }

    // 播放测试本地音频
    async playTestLocalAudio() {
        return new Promise((resolve, reject) => {
            const audio = new Audio();
            // 使用示例文件 voice/这是语音测试.mp3
            audio.src = 'voice/这是语音测试.mp3?t=' + Date.now(); // 添加时间戳防止缓存
            
            audio.oncanplay = () => {
                audio.play().then(() => {
                    console.log('本地测试音频播放成功');
                    resolve();
                }).catch(reject);
            };
            
            audio.onerror = () => {
                reject(new Error('本地测试音频文件不存在或无法播放'));
            };
            
            // 设置超时
            setTimeout(() => {
                reject(new Error('本地测试音频播放超时'));
            }, 10000);
        });
    }
}

// 语音服务配置
const VOICE_CONFIG = {
    // 腾讯云语音合成（免费额度）
    tencent: {
        enabled: true,
        baseUrl: 'https://tts.cloud.tencent.com/stream',
        // 注意：实际使用时需要申请API密钥
    },
    
    // 有道智云语音合成
    youdao: {
        enabled: true,
        baseUrl: 'https://openapi.youdao.com/ttsapi',
    },
    
    // 本地语音文件备用方案
    local: {
        enabled: false,
        audioPath: './audio/'
    }
};

// 等待DOM加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    // 预加载语音服务
    if ('speechSynthesis' in window) {
        // 预加载语音列表
        speechSynthesis.getVoices();
        
        // 监听语音列表变化
        speechSynthesis.addEventListener('voiceschanged', () => {
            console.log('语音列表已加载，可用语音数量:', speechSynthesis.getVoices().length);
            
            // 显示可用的中文语音
            const chineseVoices = speechSynthesis.getVoices().filter(voice => 
                voice.lang.includes('zh') || voice.name.includes('Chinese') || voice.name.includes('中文')
            );
            console.log('可用中文语音:', chineseVoices.map(v => v.name));
        });
        
        // 立即触发一次语音列表加载
        setTimeout(() => {
            speechSynthesis.getVoices();
        }, 100);
    }
    
    // 初始化应用
    window.wordCardApp = new WordCardApp();
    
    // 应用初始化完成，不显示语音提示
});

// 页面可见性变化时暂停语音
document.addEventListener('visibilitychange', () => {
    if (document.hidden && 'speechSynthesis' in window) {
        speechSynthesis.cancel();
    }
});